package com.own.business.login.core.hook;

import com.own.constant.ConstantAccount;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * GetUserNameHookImpl
 *
 * @author chenxueli
 * @date 2024-02-02 20:07:00
 */
@Component
public class GetUserNameHookImpl {

    private static final List<GetUserNameHook> NORMAL_USER_NAME_HOOK_LIST = new ArrayList<>();
    private static final List<GetUserNameHook> ADMIN_USER_NAME_HOOK_LIST = new ArrayList<>();
    @Resource
    private List<GetUserNameHook> getUserNameHookList;
    @Resource
    private GetUserAccountTypeHook getUserAccountTypeHook;

    @PostConstruct
    private void init() {
        getUserNameHookList
                .stream()
                .sorted(Comparator.comparing(GetUserNameHook::getUserNameOrder).reversed())
                .forEach(hook -> {
                    var accountType = hook.effectiveAccountType();
                    if (accountType == null) {
                        NORMAL_USER_NAME_HOOK_LIST.add(hook);
                        ADMIN_USER_NAME_HOOK_LIST.add(hook);
                        return;
                    }
                    if (accountType == ConstantAccount.Type.NORMAL) {
                        NORMAL_USER_NAME_HOOK_LIST.add(hook);
                    }
                    if (accountType == ConstantAccount.Type.ADMIN) {
                        ADMIN_USER_NAME_HOOK_LIST.add(hook);
                    }
                });
    }

    /**
     * 根据用户id获取用户名称
     *
     * @param userId 用户id
     * @return 用户名称
     */
    public String getUserName(Long userId) {
        return getUserName(userId, getUserAccountTypeHook.get(userId));
    }

    /**
     * 根据用户id获取用户名称
     *
     * @param userId      用户id
     * @param accountType 账号类型 1=普通账号 2=管理员
     * @return 用户名称
     */
    public String getUserName(Long userId, int accountType) {
        var list = accountType == ConstantAccount.Type.NORMAL ? NORMAL_USER_NAME_HOOK_LIST : ADMIN_USER_NAME_HOOK_LIST;
        for (var hook : list) {
            var userName = hook.getUserName(userId);
            if (StringUtils.isNotBlank(userName)) {
                return userName;
            }
        }
        return null;
    }

}
